package com.tomato.lock.common;

import lombok.AllArgsConstructor;

import java.text.MessageFormat;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@AllArgsConstructor
public class LockInterruputibly implements Runnable {
    static final Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new LockInterruputibly(), "tomato-thread-1");
        Thread t2 = new Thread(new LockInterruputibly(), "tomato-thread-2");
        t1.start();
        t2.start();
        Thread.sleep(1000);
        t2.interrupt();
    }

    @Override
    public void run() {
        try {
            lock.lockInterruptibly();
            System.out.println(MessageFormat.format("{0}获取锁成功", Thread.currentThread().getName()));
            try {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(MessageFormat.format("{0}休眠期间被中断", Thread.currentThread().getName()));
                }
            } finally {
                lock.unlock();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println(MessageFormat.format("{0}获取锁生了中断", Thread.currentThread().getName()));
        }


    }
}
